<?php

use yii\helpers\Url;

$this->context->layout = false;
//使用率
echo $this->render("@app/views/public/useRate.php")
?>
<style>
    .k-checkbox {
        display: none !important;
    }

    .selectedName {
        background: #daecf4;
        color: #003f59;
        float: left;
        text-align: center;
        padding: 5px 10px;
        margin: 5px;
        border-radius: 10px;
    }

    #affected-select-staff-treeview {
        max-height: 550px;
        margin-top: 10px;
    }

    #example {
        min-height: 200px;
    }

    #example .title {
        font-weight: bold;
        margin-bottom: 25px;
    }

    .search-wrapper {
        width: 100%;
    }

    .query-match {
        color: red;
    }

    .select-all-wrapper {
        margin-top: 20px;
        margin-bottom: 20px;
    }

    .selected-count {
        float: right;
        color: #aaa;
    }

    .k-treeview {
        border-width: 1px !important;
        padding: 5px;
    }

    #result {
        padding-bottom: 15px;
    }

    #result:after {
        content: '';
        display: block;
        clear: both;
    }
</style>
<div id="affected-staff-grid"></div>
<div id="dialog"></div>
<script type="text/x-kendo-template" id="affectedStaffTemplate">
    <input type="text" id="dateStart" name="dateStart" value="<?= $date['start'] ?>">
    <input type="text" id="dateEnd" name="dateEnd" value="<?= $date['end'] ?>">
    <a class="k-button k-button-icontext k-grid-excel" style="float:right"><span class="k-icon k-i-excel"></span>导出</a>
</script>
<script type="text/x-kendo-template" id="affected-popup-editor">
    <div class="m-box">
        <table class="table">
            <tr>
                <th width="20%">
                    <label for="department_name">部門</label>
                </th>
                <td width="30%">
                    <input id="department_name" type="text" readonly name="department_name"
                           value="#: department_name #">
                </td>
                <th width="20%"><label for="group_name">組別</label></th>
                <td width="30%">
                    <input type="text" readonly id="group_name" name="group_name" value="#: group_name #">
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="name_cn_long">中文名</label></th>
                <td width="30%">
                    <input type="text" id="name_cn_long" readonly name="name_cn_long" value="#: name_cn_long #"/>
                </td>
                <th width="20%"><label for="name_en_long">英文名</label></th>
                <td width="30%">
                    <input type="text" id="name_en_long" readonly name="name_en_long" value="#: name_en_long #"/>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="created">美國時間</label></th>
                <td width="30%">
                    <input type="text" id="created" readonly name=""
                           value="#: kendo.toString(new Date(created),'MM/dd/yyyy HH:mm') #">
                </td>
                <th width="20%"><label for="deductions_situation">扣款情況</label></th>
                <td width="30%">
                    <input type="text" id="deductions_situation" readonly
                           value="# if(typeof deductions_situation==='object'){ # 0 # }else{ # #: deductions_situation # # } #元/次"/>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="column_name">三類別</label></th>
                <td width="30%">
                    <span>#: column_name #</span>
                </td>

                <th width="20%"><label for="type_name">五大類</label></th>
                <td width="30%">
                    <span>#: type_name #</span>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="level1">錯誤一類級別</label></th>
                <td width="30%">
                    <span>#: level1 #</span>
                </td>

                <th width="20%"><label for="level2">錯誤二類級別</label></th>
                <td width="30%">
                    <span>#: level2 #</span>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="content">詳情</label></th>
                <td colspan="3">
                    <textarea readonly="readonly" style="width:100%;height:100px" id="content" name="content">#: content #</textarea>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="affectedstaff_affected_department">被影響部門</label></th>
                <td colspan="3" data-container-for="affected_department">
                    <select id="affectedstaff_affected_department" validationmessage="請選擇被影響部門"
                            name="affected_department"
                            required></select>
                </td>
            </tr>
            <tr>
                <th width="20%"><label for="affectedstaff_affected_group">被影響組別</label></th>
                <td colspan="3" data-container-for="affected_group">
                    <select id="affectedstaff_affected_group" name="affected_group"></select>
                </td>
            </tr>
            <tr>
                <th width="20%"><label>被影響人</label></th>
                <td colspan="3">
                    <button id="select-user" class="k-button" onclick="openDialog()">選擇人員</button>
                    <div id="result"
                         style="max-height: 100px; overflow: scroll;overflow-x:hidden;margin-top: 10px"></div>
                </td>
            </tr>
        </table>
    </div>
</script>
<script>
    var auth_department = <?=empty($userAuth['affected_department']) ? '[]' : json_encode($userAuth['affected_department'])?>;
    var auth_gorup = <?=empty($userAuth['affected_group']) ? '[]' : json_encode($userAuth['affected_group'])?>;
    var affected_staff_grid = $("#affected-staff-grid");
    var affectedGroup, staffs, ColumnData, thisGridId, lastGridId, isThis = true, affectedDepartment;
    var actualSelectStaff = [];
    $.ajax({
        type: "GET",
        async: false,
        url: "<?=Url::toRoute(['/hr/pick/default/groupdepartment']); ?>",
        dataType: "json",
        success: function (data) {
            affectedDepartment = data;
        }
    });
    $.ajax({
        type: "POST",
        url: "<?=Url::toRoute(['/hr/pick/default/affectedgroup']); ?>",
        data: {affectedDepartment: 'all'},
        dataType: "json",
        success: function (data) {
            affectedGroup = data;
        }
    });
    $.ajax({
        url: "<?=Url::toRoute(['/hr/pick/default/departmentstaffs']); ?>",
        dataType: "json",
        success: function (data) {
            staffs = data;
        }
    });
    $.ajax({
        type: "GET",
        url: "<?=Url::toRoute(['/hr/pick/default/gettype', 'pid' => 0]); ?>",
        dataType: "json",
        success: function (data) {
            ColumnData = data;
        }
    });

    function changeColumn(options) {
        $("#column_name").kendoDropDownList({
            dataTextField: "name",
            dataValueField: "id",
            dataSource: ColumnData,
            change: function (e) {
                var pid = e.sender._old;
                var department_id = options.model.department_id;
                var dataList = getTypeList(pid, department_id);
                var dataSource = new kendo.data.DataSource({
                    data: dataList
                });
                $("#level1").data("kendoDropDownList").select(-1);
                $("#level1").data("kendoDropDownList").setDataSource(dataSource);
                $("#level2").data("kendoDropDownList").select(-1);
                $("#level2").data("kendoDropDownList").setDataSource(_dataSource);
            }
        });
    }

    function changeAffectedDepartment(options) {
        var change = false, filter = 1;
        $("#affectedstaff_affected_department").kendoMultiSelect({
            dataTextField: "name",
            dataValueField: "id",
            dataSource: {
                transport: {
                    read: {
                        url: "<?=Url::toRoute(['/hr/pick/default/pickaffecteddepartment']); ?>",
                        dataType: "json",
                        data: function () {
                            return {"department_id": options.model.department_id, "filter": 1}
                        }
                    }
                },
                group: {field: "group"}
            },
            change: function (e) {
                var department = this.value();
                if (change) {
                    for (var o in auth_department) {
                        if (department[0] == auth_department[o]) {
                            filter = 1;
                            break;
                        }
                    }
                    var dataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "<?=Url::toRoute(['/hr/pick/default/pickaffecteddepartment']); ?>",
                                dataType: "json",
                                data: function () {
                                    return {department_id: options.model.department_id, "filter": filter};
                                }
                            }
                        },
                        group: {field: "group"}
                    });
                    $("#affectedstaff_affected_department").data("kendoMultiSelect").setDataSource(dataSource);
                    change = false;
                }
                if (department.length === 0) {
                    var dataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "<?=Url::toRoute(['/hr/pick/default/pickaffecteddepartment']); ?>",
                                dataType: "json",
                                data: function () {
                                    return {department_id: options.model.department_id};
                                }
                            }
                        },
                        group: {field: "group"}
                    });
                    $("#affectedstaff_affected_department").data("kendoMultiSelect").setDataSource(dataSource);
                    change = true;
                    filter = 0;
                }
                var dataSource = new kendo.data.DataSource({
                    transport: {
                        read: {
                            url: "<?=Url::toRoute(['/hr/pick/default/pickaffectedgroup']); ?>",
                            dataType: "json",
                            type: "POST",
                            data: function () {
                                return {affectedDepartment: department, "filter": filter};
                            }
                        }
                    },
                    group: {field: "group"}
                });
                var affectedstaffAffectedGroup = $("#affectedstaff_affected_group").data("kendoMultiSelect");
                affectedstaffAffectedGroup.setDataSource(dataSource);
                if (filter) {
                    $("#select-user").attr("disabled", false);
                    var AffectedStaffDataSource = false;
                    AffectedStaffDataSource = new kendo.data.HierarchicalDataSource({
                        transport: {
                            read: function (e) {
                                $.ajax({
                                    type: "POST",
                                    url: "/index.php?r=hr%2Fpick%2Fdefault%2Fgettreeviewstaff",
                                    dataType: "json",
                                    data: {
                                        affectedDepartment: department,
                                        affectedGroup: affectedstaffAffectedGroup.value()
                                    },
                                    success: function (result) {
                                        e.success(result);
                                    }
                                })
                            }
                        },
                        schema: {
                            model: {
                                id: "id",
                                hasChildren: true,
                                children: "items"
                            }
                        }
                    });
                    var loading = setInterval(function () {
                        if (AffectedStaffDataSource) {
                            $("#affected-select-staff-treeview").data("kendoTreeView").setDataSource(AffectedStaffDataSource);
                            AffectedStaffDataSource.fetch(function () {
                                updateAffectedStaff(AffectedStaffDataSource.data());
                            });
                            clearInterval(loading);
                        }
                    }, 1200);
                } else {
                    actualSelectStaff = [];
                    updateResult(actualSelectStaff);
                    updateUserId();
                    $("#select-user").attr("disabled", true);
                }
            }
        });
    }

    function changeAffectedGroup(options) {
        var changeGroup = false, filterGroup = 1;
        $("#affectedstaff_affected_group").kendoMultiSelect({
            dataTextField: "unit_name",
            dataValueField: "id",
            dataSource: {
                transport: {
                    read: {
                        url: "<?=Url::toRoute(['/hr/pick/default/pickaffectedgroup']); ?>",
                        dataType: "json",
                        type: "POST",
                        data: function () {
                            var department = [];
                            var length = options.model.affected_department.length;
                            for (var o = 0; o < length; o++) {
                                if (typeof options.model.affected_department[o] === 'object') {
                                    department.push(options.model.affected_department[o].id);
                                } else {
                                    department.push(options.model.affected_department[o]);
                                }
                            }
                            return {affectedDepartment: department, "filter": 1};
                        }
                    }
                },
                group: {field: "group"}
            },
            change: function (e) {
                var group = this.value();
                var department = $("#affectedstaff_affected_department").data("kendoMultiSelect").value();
                if (changeGroup) {
                    for (var o in auth_gorup) {
                        if (group[0] == auth_gorup[o]) {
                            filterGroup = 1;
                            break;
                        }
                    }
                    var dataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "<?=Url::toRoute(['/hr/pick/default/pickaffectedgroup']); ?>",
                                dataType: "json",
                                type: "POST",
                                data: function () {
                                    return {affectedDepartment: department, "filter": filterGroup};
                                }
                            }
                        },
                        group: {field: "group"}
                    });
                    $("#affectedstaff_affected_group").data("kendoMultiSelect").setDataSource(dataSource);
                    changeGroup = false;
                }
                if (group.length === 0) {
                    var dataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "<?=Url::toRoute(['/hr/pick/default/pickaffectedgroup']); ?>",
                                dataType: "json",
                                type: "POST",
                                data: function () {
                                    return {affectedDepartment: department};
                                }
                            }
                        },
                        group: {field: "group"}
                    });
                    $("#affectedstaff_affected_group").data("kendoMultiSelect").setDataSource(dataSource);
                    changeGroup = true;
                    filterGroup = 0;
                }
//                if (filterGroup) {
                var AffectedStaffDataSource = false;
                AffectedStaffDataSource = new kendo.data.HierarchicalDataSource({
                    transport: {
                        read: function (e) {
                            $.ajax({
                                type: "POST",
                                url: "/index.php?r=hr%2Fpick%2Fdefault%2Fgettreeviewstaff",
                                dataType: "json",
                                data: {affectedDepartment: department, affectedGroup: group},
                                success: function (result) {
                                    e.success(result);
                                }
                            })
                        }
                    },
                    schema: {
                        model: {
                            id: "id",
                            hasChildren: true,
                            children: "items"
                        }
                    }
                });
                var loading = setInterval(function () {
                    if (AffectedStaffDataSource) {
                        $("#affected-select-staff-treeview").data("kendoTreeView").setDataSource(AffectedStaffDataSource);
                        AffectedStaffDataSource.fetch(function () {
                            updateAffectedStaff(AffectedStaffDataSource.data());
                        });
                        clearInterval(loading);
                    }
                }, 1200);
//                } else {
//                    $("#select-user").attr("disabled", true);
//                }
            }
        });
    }

    function changeAffectedStaff(e) {
        actualSelectStaff = [];
        for (var o in staffs) {
            for (var i in e.model.affected_staff) {
                if (staffs[o]['id'] == e.model.affected_staff[i]) {
                    actualSelectStaff.push({
                        id: staffs[o]['id'],
                        name: staffs[o]['name'],
                        department: staffs[o]['department_name'],
                        group: staffs[o]['group_name']
                    });
                }
            }
        }
        updateResult(actualSelectStaff);
    }

    function treeViewDataBound(e) {
        e.sender.expand(e.node); //展开全部节点
    }

    function initOpen(e) {
        $('#employees-search').keydown(function () {
            if (event.keyCode == 13) {
                var query = this.value.toLowerCase();
                var dataSource = $("#affected-select-staff-treeview").data("kendoTreeView").dataSource;
                filter(dataSource, query);
                matchColors(query);
            }
        });
        $("#employees-search").next().click(function () {
            var query = $("#employees-search").val().toLowerCase();
            var dataSource = $("#affected-select-staff-treeview").data("kendoTreeView").dataSource;
            filter(dataSource, query);
            matchColors(query);
        });
    }

    function dialogOpen(e) {
        setTimeout(function () {
            $(".selected-count").html("已選擇" + actualSelectStaff.length + "個人員");
            var treeView = $("#affected-select-staff-treeview").data("kendoTreeView");
            for (var o in actualSelectStaff) {
                var bar = treeView.findByText(actualSelectStaff[o]['name']);
                if (treeView.dataItem(bar)) {
                    treeView.dataItem(bar).set("checked", true);
                }
            }
            $("#employees-search").focus().select();
        })
    }

    function openDialog(e) {
        $("#dialog").data("kendoDialog").open();
    }

    function actionOK(e) {
        var treeView = $("#affected-select-staff-treeview").data("kendoTreeView");
        actualSelectStaff = getCheckedItems(treeView);
        for (var o in staffs) {
            for (var i in actualSelectStaff) {
                if (staffs[o]['id'] == actualSelectStaff[i]['id']) {
                    actualSelectStaff[i]['department'] = staffs[o]['department_name'];
                    actualSelectStaff[i]['group'] = staffs[o]['group_name'];
                }
            }
        }
        updateResult(actualSelectStaff);
        updateUserId();
    }

    function updateResult(actualSelectStaff) {
        if (actualSelectStaff.length > 0) {
            var result = "";
            for (var i = 0; i < actualSelectStaff.length; i++) {
                result += '<li id="' + actualSelectStaff[i].id + '" class="k-button"><span>' + actualSelectStaff[i].name + ' [' + actualSelectStaff[i].department + ']</span><span class="k-icon k-i-close" onclick="removeStaff(\'' + i + '\')">delete</span></span></li>';
            }
        } else {
            result = "沒有選擇人員";
        }
        $("#result").html(result);
    }

    function treeViewCheck(e) {
        setTimeout(function () {
            updateSelectedCount(e.sender);
        })
    }

    function selectAll(sender) {
        $("#affected-select-staff-treeview .k-checkbox").removeAttr("checked").prop("checked", sender.checked);
        $("#affected-select-staff-treeview .k-checkbox").trigger("change");
    }

    //更新選擇數量
    function updateSelectedCount(treeView) {
        $(".selected-count").html("已選擇" + getCheckedItems(treeView).length + "個人員");
    }

    //获取选择item数量
    function getCheckedItems(treeView) {
        var nodes = treeView.dataSource.data();
        return getCheckedNodes(nodes);
    }

    //获取选择节点
    function getCheckedNodes(nodes) {
        var node, childCheckedNodes;
        var checkedNodes = [];
        for (var i = 0; i < nodes.length; i++) {
            node = nodes[i];
            if (node.hasChildren) {
                childCheckedNodes = getCheckedNodes(node.children.data());
                if (childCheckedNodes.length > 0) {
                    checkedNodes = checkedNodes.concat(childCheckedNodes);
                }
            }
            if (node.checked && !node.hasOwnProperty("expanded")) {
                checkedNodes.push(node);
            }
        }
        return checkedNodes;
    }

    //實際搜索
    function filter(dataSource, query) {
        var hasVisibleChildren = false;
        var data = dataSource instanceof kendo.data.HierarchicalDataSource && dataSource.data();
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            var text = item.name.toLowerCase();
            var itemVisible =
                query === true // parent already matches
                || query === "" // query is empty
                || text.indexOf(query) >= 0; // item text matches query
            var anyVisibleChildren = filter(item.children, itemVisible || query); // pass true if parent matches
            hasVisibleChildren = hasVisibleChildren || anyVisibleChildren || itemVisible;
            item.hidden = !itemVisible && !anyVisibleChildren;
        }
        if (data) {
            dataSource.filter({field: "hidden", operator: "neq", value: true});
        }
        return hasVisibleChildren;
    }

    //標記搜索顏色
    function matchColors(query, element) {
        $("#affected-select-staff-treeview .k-in:containsIgnoreCase('" + query + "')").each(function () {
            var index = $(this).html().toLowerCase().indexOf(query.toLowerCase());
            var length = query.length;
            var original = $(this).html().substr(index, length);
            var newText = $(this).html().replace(original, "<span class='query-match'>" + original + "</span>");
            $(this).html(newText);
        });
    }

    //Edit 去除被影响人员
    function removeStaff(index) {
        actualSelectStaff.splice(index, 1);
        updateResult(actualSelectStaff);
        updateUserId();
    }

    //更新grid 被影响人
    function updateUserId() {
        var selectUserId = [];
        for (var o in actualSelectStaff) {
            selectUserId.push(actualSelectStaff[o]['id']);
        }
        var dataItem = affected_staff_grid.data("kendoGrid").dataSource.get(thisGridId);
        dataItem.set("affected_staff", selectUserId);
    }

    //更新选择的被影响人
    function updateAffectedStaff(affectedStaffData) {
        var optionalAffectedStaffs = optionalAffectedStaff(affectedStaffData);
        for (var o in actualSelectStaff) {
            if (!isInArray(optionalAffectedStaffs, actualSelectStaff[o].id)) {
                delete actualSelectStaff[o];
            }
        }
        var a = actualSelectStaff;
        var b = [];//去除undefined后的结果
        for (var i = 0; i < a.length; i++) {
            if (typeof(a[i]) !== 'undefined') {
                b.push(a[i]);
            }
        }
        actualSelectStaff = b;
        updateResult(actualSelectStaff);
        updateUserId();
    }

    //判断一个元素是否存在于一个数组中
    function isInArray(arr, value) {
        for (var i = 0; i < arr.length; i++) {
            if (value === arr[i].id) {
                return true;
            }
        }
        return false;
    }

    //可以选择的被影响人
    function optionalAffectedStaff(affectedStaffData) {
        var node, optionalAffectedStaffs;
        var optionalAffectedStaffData = [];
        for (var i = 0; i < affectedStaffData.length; i++) {
            node = affectedStaffData[i];
            if (node.items.length) {
                optionalAffectedStaffs = optionalAffectedStaff(node.items);
                if (optionalAffectedStaffs.length > 0) {
                    optionalAffectedStaffData = optionalAffectedStaffData.concat(optionalAffectedStaffs);
                }
            } else {
                optionalAffectedStaffData.push(node)
            }

        }
        return optionalAffectedStaffData;
    }

    function initTreeStaff(option) {
        if (isThis) {
            if (!$("#affected-select-staff-treeview").data("kendoTreeView")) {
                $("#affected-select-staff-treeview").kendoTreeView({
                    dataSource: {
                        transport: {
                            read: function (e) {
                                var affectedDepartment = [];
                                for (var o = 0; o < option.model.affected_department.length; o++) {
                                    if (typeof option.model.affected_department[o]['id'] == 'string') {
                                        affectedDepartment.push(option.model.affected_department[o]['id']);
                                    } else {
                                        affectedDepartment.push(option.model.affected_department[o]);
                                    }
                                }
                                var affectedGroup = [];
                                for (var o = 0; o < option.model.affected_group.length; o++) {
                                    if (typeof option.model.affected_group[o]['id'] == 'string') {
                                        affectedGroup.push(option.model.affected_group[o]['id']);
                                    } else {
                                        affectedGroup.push(option.model.affected_group[o]);
                                    }
                                }
                                $.ajax({
                                    type: "POST",
                                    url: "/index.php?r=hr%2Fpick%2Fdefault%2Fgettreeviewstaff",
                                    dataType: "json",
                                    data: {affectedDepartment: affectedDepartment, affectedGroup: affectedGroup},
                                    success: function (result) {
                                        e.success(result);
                                    }
                                });
                            }
                        },
                        schema: {
                            model: {
                                id: "id",
                                hasChildren: true,
                                children: "items"
                            }
                        }
                    },
                    dataTextField: "name",
                    checkboxes: {
                        checkChildren: true
                    },
                    loadOnDemand: false,
                    expandAll: true,
                    dataBound: treeViewDataBound,
                    check: treeViewCheck
                });
            } else {
                $("#affected-select-staff-treeview").data("kendoTreeView").setDataSource(
                    new kendo.data.HierarchicalDataSource({
                        transport: {
                            read: function (e) {
                                var affectedDepartment = [];
                                for (var o = 0; o < option.model.affected_department.length; o++) {
                                    if (typeof option.model.affected_department[o]['id'] == 'string') {
                                        affectedDepartment.push(option.model.affected_department[o]['id']);
                                    } else {
                                        affectedDepartment.push(option.model.affected_department[o]);
                                    }
                                }
                                var affectedGroup = [];
                                for (var o = 0; o < option.model.affected_group.length; o++) {
                                    if (typeof option.model.affected_group[o]['id'] == 'string') {
                                        affectedGroup.push(option.model.affected_group[o]['id']);
                                    } else {
                                        affectedGroup.push(option.model.affected_group[o]);
                                    }
                                }
                                $.ajax({
                                    type: "POST",
                                    url: "/index.php?r=hr%2Fpick%2Fdefault%2Fgettreeviewstaff",
                                    dataType: "json",
                                    data: {affectedDepartment: affectedDepartment, affectedGroup: affectedGroup},
                                    success: function (result) {
                                        e.success(result);
                                    }
                                });
                            }
                        },
                        schema: {
                            model: {
                                id: "id",
                                hasChildren: true,
                                children: "items"
                            }
                        }
                    })
                );
            }
        }
    }

    $(document).ready(function () {
        affected_staff_grid.kendoGrid({
            dataSource: {
                transport: {
                    read: function (e) {
                        $.ajax({
                            data: {dateStart: $("#dateStart").val(), dateEnd: $("#dateEnd").val()},
                            url: "<?=Url::toRoute(['/hr/pick/default/affectedpeople']);?>",
                            type: 'get',
                            dataType: 'json',
                            success: function (res) {
                                e.success(res);
                            }
                        })
                    },
                    update: function (e) {
                        for (var o in e.data.affected_department) {
                            if (typeof e.data.affected_department[o]['id'] == 'string') {
                                e.data.affected_department[o] = e.data.affected_department[o]['id'];
                            }
                        }
                        for (var o in e.data.affected_group) {
                            if (typeof e.data.affected_group[o]['id'] == 'string') {
                                e.data.affected_group[o] = e.data.affected_group[o]['id'];
                            }
                        }
                        $.ajax({
                            url: "<?=Url::to(['updateaffected']); ?>",
                            dataType: "json",
                            type: "POST",
                            data: e.data,
                            success: function (redata) {
                                if (redata.status == 1) {
                                    e.success(redata.update_data);
                                } else {
                                    layer.msg(redata.info, {icon: 5});
                                }
                            }
                        })
                    }
                },
                schema: {
                    model: {
                        id: "id",
                        fields: {
                            id: {field: "id", editable: false, nullable: true},
                            created: {field: "created", type: "date"},
                            department_name: {field: "department_name"},
                            group_name: {field: "group_name"},
                            name_en_long: {field: "name_en_long"},
                            level1: {field: "level1"},
                            level2: {field: "level2"},
                            content: {field: "content"},
                            affected_group: {field: "affected_group", type: "object"},
                            affected_staff: {field: "affected_staff", type: "object"},
                            affected_department: {field: "affected_department", type: "object"}
                        }
                    }
                },
                pageSize: 20
            },
            sortable: true,
            filterable: {
                extra: false,
                operators: {
                    string: {
                        contains: "包含",
                        doesnotcontain: "不包含",
                        eq: "等于",
                        neq: "不等于"
                    }
                }
            },
            toolbar: kendo.template($("#affectedStaffTemplate").html()),
            pageable: {
                refresh: true,//刷新按钮
                pageSizes: [20, 40, 60, "all"],//每页数量选择
                buttonCount: 5//页码按钮数量
            },
            excel: {
                allPages: true,
                fileName: "被影響人.xlsx",
                filterable: true
            },
            excelExport: function (e) {
                for (var i = 0; i < e.data.length; i++) {
                    var html = "";
                    for (var b = 0; b < e.data[i].affected_group.length; b++) {
                        for (var o in affectedGroup) {
                            if (affectedGroup[o].id == e.data[i].affected_group[b]) {
                                html += affectedGroup[o].unit_name + ',';
                            }
                        }
                    }
                    if (html !== "") {
                        html = html.replace(/,$/, '');
                        e.workbook.sheets[0].rows[i + 1].cells[7] = {value: html};
                    } else {
                        for (var b = 0; b < e.data[i].affected_department.length; b++) {
                            for (var o in affectedDepartment) {
                                if (affectedDepartment[o].id == e.data[i].affected_department[b]) {
                                    if (affectedDepartment[o].hasChildren) {
                                        html = "未選擇";
                                    } else {
                                        html = "無";
                                    }
                                }
                            }
                        }
                    }
                    e.workbook.sheets[0].rows[i + 1].cells[7] = {value: html};
                    html = '';
                    for (var b = 0; b < e.data[i].affected_staff.length; b++) {
                        for (var o in staffs) {
                            if (staffs[o].id == e.data[i].affected_staff[b]) {
                                html += staffs[o].name + ' [' + staffs[o].group_name + '],';
                            }
                        }
                    }
                    html = html.replace(/,$/, '');
                    e.workbook.sheets[0].rows[i + 1].cells[8] = {value: html};
                }
            },
            editable: {
                mode: "popup",
                template: kendo.template($("#affected-popup-editor").html()),
                window: {
                    animation: {
                        close: {
                            effects: "fade:out"
                        },
                        open: {
                            effects: "fade:in"
                        }
                    },
                    close: function () {
                        $(".k-edit-form-container").remove();
                        $(document).unbind("scroll.unable");
//                        $("#affectedstaff_affected_department").data("kendoMultiSelect").destroy();
//                        $("#affectedstaff_affected_group").data("kendoMultiSelect").destroy();
                    }
                }
            },
            edit: function (e) {
                thisGridId = e.model.id;
                if (thisGridId === lastGridId) {
                    isThis = false;
                } else {
                    isThis = true;
                }
                $(".k-edit-form-container").parent().width(800).height(720).data("kendoWindow").center();
                $(".k-edit-form-container").width("100%");
                changeAffectedDepartment(e);
                changeAffectedGroup(e);
                changeAffectedStaff(e);
                var top = $(document).scrollTop();
                $(document).on('scroll.unable', function (e) {
                    $(document).scrollTop(top);
                });
                initTreeStaff(e);
            },
            columns: [
                {
                    hidden: true,
                    field: "affected_department",
                    title: "被影響的部門"
                },
                {
                    field: "created",
                    title: "發佈時間",
                    format: "{0:MM/dd/yyyy}",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "98px"
                },
                {
                    field: "department_name",
                    title: "部门",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "98px"
                },
                {
                    field: "group_name",
                    title: "组别",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "98px"
                },
                {
                    field: "username",
                    title: "發佈人",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "98px"
                },
                {
                    field: "level1",
                    title: "LEVEL 1",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "120px"
                },
                {
                    field: "level2",
                    title: "LEVEL 2",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "120px"
                },
                {
                    field: "content",
                    title: "詳情",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    width: "360"
                },
                {
                    field: "affected_group",
                    title: "被影響的組",
                    width: "169px",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    template: function (e) {
                        var data = new Array();
                        for (var b = 0; b < e.affected_group.length; b++) {
                            for (var o in affectedGroup) {
                                if (affectedGroup[o].id == e.affected_group[b]) {
                                    data.push(affectedGroup[o].unit_name);
                                }
                            }
                        }
                        if (data.length > 0) {
                            return data;
                        } else {
                            var html = "";
                            for (var b = 0; b < e.affected_department.length; b++) {
                                for (var o in affectedDepartment) {
                                    if (affectedDepartment[o].id == e.affected_department[b]) {
                                        if (affectedDepartment[o].hasChildren) {
                                            html = "未選擇";
                                        } else {
                                            html = "無";
                                        }
                                    }
                                }
                            }
                            return html;
                        }
                    }
                }
                ,
                {
                    field: "affected_staff",
                    title: "被影響的人",
                    width: "169px",
                    headerAttributes: alignCenterAttribute,
                    attributes: alignCenterAttribute,
                    template: function (e) {
                        var data = new Array();
                        for (var b = 0; b < e.affected_staff.length; b++) {
                            for (var o in staffs) {
                                if (staffs[o].id == e.affected_staff[b]) {
                                    data.push(staffs[o].name + ' [' + staffs[o].group_name + ']');
                                }
                            }
                        }
                        return data;
                    }
                },
                {
                    command: ["edit"],
                    title: "操作",
                    width: "88px"
                }
            ]
        });
        $("#dateStart").kendoDatePicker({
            format: "yyyy/MM/dd",
            culture: "zh-CN",
            change: function (e) {
                var __grid = affected_staff_grid.data("kendoGrid");
                __grid.dataSource.read();
                __grid.refresh();
            }
        });
        $("#dateEnd").kendoDatePicker({
            format: "yyyy/MM/dd",
            culture: "zh-CN",
            change: function (e) {
                var __grid = affected_staff_grid.data("kendoGrid");
                __grid.dataSource.read();
                __grid.refresh();
            }
        });
        $("#dialog").kendoDialog({
            width: "800px",
            height: "800px",
            visible: false,
            title: "选择人员",
            closable: true,
            modal: false,
            content: "<div class='k-textbox k-space-right search-wrapper'><input id='employees-search' type='text'  placeholder='回车搜索'/><span class='k-icon k-i-search'></span></div>" +
            "<div class='select-all-wrapper'><input data-role='checkbox' onchange='selectAll(this)' type='checkbox' class='k-checkbox' id='_selectAllEmployees'/><label class='k-checkbox-label' for='_selectAllEmployees'>&nbsp;選擇全部</label><span class='selected-count'></span></div>" +
            "<div id='affected-select-staff-treeview'></div>",
            actions: [
                {text: 'Cancel'},
                {text: 'OK', primary: true, action: actionOK}
            ],
            initOpen: initOpen,
            open: dialogOpen,
            close: function () {
                var treeView = $("#affected-select-staff-treeview").data("kendoTreeView");
                var checkedNodes = getCheckedItems(treeView);
                for (var o in checkedNodes) {
                    var bar = treeView.findByText(checkedNodes[o]['name']);
                    if (treeView.dataItem(bar)) {
                        treeView.dataItem(bar).set("checked", false);
                    }
                }
            }
        });
        $.expr[':'].containsIgnoreCase = function (n, i, m) {
            return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
        };
    });
</script>